package cn.xspace.module.other.application;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.squareup.picasso.Picasso;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.xspace.android.xafcommon.appliction.BaseApplication;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import cn.xspace.library.http.MInterceptor;
import cn.xspace.library.http.OkHttpDownLoader;
import cn.xspace.library.util.BuildCache;
import cn.xspace.wnx.util.HuanXinHelper;
import okhttp3.Cache;
import okhttp3.OkHttpClient;

/**
 * @version V1.0.0
 * @ClassName: MyApplictiton
 * @author:qbluo
 * @Date：2014-2-20
 */
public class MyApplication extends BaseApplication {

    private static final String TAG = MyApplication.class.getSimpleName();

    @Override
    public void onCreate() {
        super.onCreate();
        if (!myProgressCheck())
            return;
        UMShareAPI.get(this);
        PlatformConfig.setWeixin(BuildCache.getAppConfigBean(mInstance).appInfo.WXAppId, BuildCache.getAppConfigBean
                (mInstance).appInfo.WXAppSecret);
//        ClassUtil.getOtherMethod(ClassUtil.getMethod(ClassUtil.HuanXinHelper, "getInstance"), "init");

        HuanXinHelper.getInstance().init();
//        SDKInitializer.initialize(mInstance);
//        startLoc();

        //构造自带本地缓存的 Picasso 和okhttp配合使用
        //缓存目录
        File file = new File(this.getCacheDir(), "okhttp");
        OkHttpClient client = new OkHttpClient
                .Builder()
                .addInterceptor(new MInterceptor())
                .cache(new Cache(file, 1024 * 1024 * 100)).build();
        Picasso picasso = new Picasso.Builder(this)
                .downloader(new OkHttpDownLoader(client))
//                .loggingEnabled(true)
                .build();
        //设置单例
        Picasso.setSingletonInstance(picasso);
//        MCrashHandle.getInstance().init(this);
    }

    /**
     * check the application process name if process name is not qualified, then
     * we think it is a service process and we will not init SDK
     *
     * @param pID
     * @return
     */
    protected String getAppName(int pID) {
        Log.v(TAG, "getAppName pID: " + pID);
        String processName = null;
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = mContext.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            // LogUtil.v(TAG, "Id: "+ info.pid
            // +" ProcessName: "+info.processName );
            try {
                if (info.pid == pID) {
                    CharSequence c = pm
                            .getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
                    // Log.v(TAG, "Id: "+ info.pid +" ProcessName: "+
                    // info.processName +"  Label: "+c.toString());
                    // processName = c.toString();
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return null;
    }


    /**
     * 是否当前包进程
     *
     * @return
     */
    protected boolean myProgressCheck() {
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
        Log.d(TAG, "process app name : " + processAppName + " " + getPackageName());
        // 如果app启用了远程的service，此application:onCreate会被调用2次
        // 默认的app会在以包名为默认的process name下运行，如果查到的process name不是app的process
        // name就立即返回
        if (processAppName == null || !processAppName.equalsIgnoreCase(getPackageName())) {
            Log.e(TAG, "enter the service process!");
            return false;
        }
        return true;
    }

    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }

    public String getPackage() {
        return getPackageName();
    }

    public void startLoc() {
//        Intent mIntent = new Intent(mContext, LocationService.class);
//        startService(mIntent);
//        MyAMapLocation.getInstance().startLocation();
    }


}
